package com.uenpay.im.ui.old.activity.chat.manage;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout.LayoutParams;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.StringUtils;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.message.type.MenuMsgType;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.QyxMsg;
import com.qyx.android.protocol.QyxMsgView;
import com.qyx.android.protocol.QyxTopMsg;
import com.qyx.android.utilities.DateUtils;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ChatActivity;
import com.uenpay.im.ui.old.activity.chat.DialogLoadingActivity;
import com.uenpay.im.ui.old.activity.mycollect.CollectHandle;
import com.uenpay.im.ui.old.activity.red.ReceiveRedDialogActivity;
import com.uenpay.im.ui.old.activity.red.ReceiveRedEntity;
import com.uenpay.im.ui.old.activity.red.RedDetailActivity;
import com.uenpay.im.ui.old.activity.red.RedDetailPersonalActivity;
import com.uenpay.im.ui.old.activity.red.RedHandler;
import com.uenpay.im.ui.old.activity.stickers.StickersHandle;
import com.uenpay.im.ui.old.activity.videochat.CallActivity;
import com.uenpay.im.adapter.TalkLongClickViewAdapter;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.TalkLongClickViewEntity;
import com.uenpay.im.entities.chatbean.AttachModel;
import com.uenpay.im.entities.chatbean.MsgGifModel;
import com.uenpay.im.entities.chatbean.MsgImageModel;
import com.uenpay.im.invokeitems.chat.OnAttachedListener;
import com.uenpay.im.invokeitems.chat.UploadMessageAttachment;
import com.uenpay.im.service.MsgContentType2Name;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.MyDialog;
import com.qyx.videochat.util.ExtraVideoConstant;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author SL
 * @created 2016-1-3 上午11:30:58
 * @copyRight http://www.qiyunxin.com
 * @function 对话列表辅助类
 */
public class ChatMsgManage {

	private CollectHandle mCollectHandle = new CollectHandle();
	private TalkMsgManager takeMsgManager = null;
	private TopListMsgManager topListMsgManager = null;
	private Context mContext = null;

	public ChatMsgManage() {

	}

	public ChatMsgManage(Context _Context) {
		takeMsgManager = new TalkMsgManager();
		topListMsgManager = new TopListMsgManager();
		mContext = _Context;
	}

	/**
	 * 录音中语音动画数组（PS：图片）
	 */
	public static final int[] audioRecordVolumeResource = new int[] {
			R.drawable.icon_audio_record_volume1,
			R.drawable.icon_audio_record_volume2,
			R.drawable.icon_audio_record_volume3,
			R.drawable.icon_audio_record_volume4,
			R.drawable.icon_audio_record_volume5 };

	/**
	 * View长按事件
	 *
	 * @param v
	 * @param iDeleteMsg
	 * @return
	 */
	public boolean viewLongClick(View v, final IDeleteOrWithdrawMsg iDeleteMsg) {
		QyxMsgView qyxMsgView = (QyxMsgView) v.getTag();
		if (qyxMsgView == null || qyxMsgView.msg == null)
			return true;
		final QyxMsg msg = qyxMsgView.msg;
		final int type = Integer.valueOf(msg.msg_content_type);
		if (type == MsgContentType.ACCESS_FRIEND_VERIFY) {
			return true;
		}
		final MyDialog.Builder dlg = new MyDialog.Builder(mContext);
		if ((msg.from_cust_id + "").equals(IMApplication.getCustId())) {
			if (!TextUtils.isEmpty(IMApplication.config.getUserName())) {
				dlg.setTitle(IMApplication.config.getUserName());
			} else {
				dlg.setTitle(R.string.dialog_title);
			}
		} else {
			if (!TextUtils.isEmpty(msg.from_cust_name)) {
				dlg.setTitle(msg.from_cust_name);
			} else {
				dlg.setTitle(R.string.dialog_title);
			}
		}

		final ListView menus = new ListView(mContext);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		menus.setDivider(new ColorDrawable(mContext.getResources().getColor(
				R.color.layout_division_view)));
		menus.setDividerHeight(1);
		menus.setLayoutParams(params);
		TalkLongClickViewAdapter adapter = null;
		if (type == MsgContentType.AUDIO || type == MsgContentType.LOCATION
				|| type == MsgContentType.FILE
				|| type == MsgContentType.VIDEO
				|| type == MsgContentType.BUSINESS_CRAD) {
			adapter = new TalkLongClickViewAdapter(mContext,
					ChatLongClickTextManage.getOtherData(msg.from_cust_id + ""));
		} else if (type == MsgContentType.GIF_EXP) {
			MsgGifModel msgGifModel = (MsgGifModel) msg.baseContentModel;
			adapter = new TalkLongClickViewAdapter(mContext,
					ChatLongClickTextManage.getGifData(msg.from_cust_id + "",
							msgGifModel));
		} else if (type == MsgContentType.TEXT) {
			adapter = new TalkLongClickViewAdapter(mContext,
					ChatLongClickTextManage.getTextData(msg.from_cust_id + ""));
		} else if (type == MsgContentType.RED
				|| type == MsgContentType.REQUEST_VIDEO_CHAT
				|| type == MsgContentType.OA_APPROVAL
				|| type == MsgContentType.OA_REIMBURSEMENT
				|| type == MsgContentType.OA_NOTICE
				|| type == MsgContentType.OA_TASK
				|| type == MsgContentType.CROWD_FUND || type == 10002
				|| type == MsgContentType.TRANSFER_ACCOUNTS
				|| type == MsgContentType.PUBLIC_NUM_NEWS) {
			/**
			 * 红包和视频通话记录只显示删除
			 */
			adapter = new TalkLongClickViewAdapter(mContext,
					ChatLongClickTextManage.getOnlyDeleteData());
		} else {
			adapter = new TalkLongClickViewAdapter(mContext,
					ChatLongClickTextManage.getImageData(msg.from_cust_id + ""));
		}
		if (adapter != null) {
			menus.setAdapter(adapter);
		}
		dlg.setListView(menus);
		dlg.setMessage("");
		// dlg.setTitle(R.string.action_dialog_title);
		dlg.create().show();
		menus.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				TalkLongClickViewEntity mTalkLongClickViewEntity = (TalkLongClickViewEntity) arg0
						.getAdapter().getItem(arg2);
				if (mTalkLongClickViewEntity != null) {
					if (mTalkLongClickViewEntity.type == MenuMsgType.COPY) {
						String copy_str = msg.content;
						copy_str = msg.content;
						if (!TextUtils.isEmpty(copy_str)) {
							if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
								android.text.ClipboardManager clipboard = (android.text.ClipboardManager) mContext
										.getSystemService(Context.CLIPBOARD_SERVICE);
								clipboard.setText(copy_str);
							} else {
								android.content.ClipboardManager clipboard = (android.content.ClipboardManager) mContext
										.getSystemService(Context.CLIPBOARD_SERVICE);
								android.content.ClipData clip = android.content.ClipData
										.newPlainText("Copied Text", copy_str);
								clipboard.setPrimaryClip(clip);
							}
							IMApplication
									.showToast(R.string.text_copied_to_the_clipboard);
						}
					} else if (mTalkLongClickViewEntity.type == MenuMsgType.FORWARD) {
						((ChatActivity) mContext)
								.startForwardMessagePickFriend(msg);
					} else if (mTalkLongClickViewEntity.type == MenuMsgType.DELETE) {
						iDeleteMsg.onDeleteMsg(msg);
					} else if (mTalkLongClickViewEntity.type == MenuMsgType.COLLECT) {
						collect(msg);
					} else if (mTalkLongClickViewEntity.type == MenuMsgType.WITHDRAW) {
						/** 将点击的消息对象状态修改为待删除（不修改数据库，只修改显示出来的消息对象） **/
						// 撤销消息
						checkMsgTime(msg, iDeleteMsg);
					} else if (mTalkLongClickViewEntity.type == MenuMsgType.ADD_TO_STICKERS) {
						/** 添加到表情 **/
						addSticker(msg);
					}
					dlg.getDialog().dismiss();
				}
			}
		});
		dlg.getDialog().setCancelable(true);
		return true;

	}

	/**
	 * 发送gif图片时,png图片名称转换为gif图片名称
	 *
	 * @param pngName
	 *            png图片名称
	 * @return gif图片名称
	 */
	public static String getGifName(String pngName) {
		try {
			String str[] = pngName.split("_");
			String gif_name = str[0] + "_" + str[1];
			String name = gif_name + ".gif";
			return name;
		} catch (Exception e) {
			return "";
		}
	}

	// public class AnimateFirstDisplayListener implements OnProgressListener {
	// View _view = null;
	// View _group_view = null;
	// boolean _showMin = false;
	//
	// public AnimateFirstDisplayListener(View v, View gv, boolean showMin) {
	// _view = v;
	// _group_view = gv;
	// _showMin = showMin;
	// }
	//
	// @Override
	// public void OnProgress(long total_bytes, long downloaded_bytes) {
	// }
	//
	// @Override
	// public void OnSuccess(View v) {
	// if (_view != null) {
	// if (v instanceof MaskImageView) {
	// MaskImageView iv = (MaskImageView) v;
	// if (iv == null || iv.getDrawable() == null) {
	// return;
	// }
	// Bitmap bitmap = ((BitmapDrawable) iv.getDrawable())
	// .getBitmap();
	// if (bitmap != null) {
	// android.view.ViewGroup.LayoutParams linearParams = _view
	// .getLayoutParams();
	// int h = bitmap.getHeight();
	// int w = bitmap.getWidth();
	// int s_w = 0;
	// if (_showMin) {
	// s_w = Math.min(Utils.dip2px(mContext, 100), w);
	// } else {
	// s_w = Math.max(Utils.dip2px(mContext, 100), w);
	// }
	// int s_h = (int) (s_w / (w * 1.0 / h));
	//
	// ViewGroup.LayoutParams ivLinearParams = iv
	// .getLayoutParams();
	// ivLinearParams.height = s_h;
	// ivLinearParams.width = s_w;
	// iv.setLayoutParams(ivLinearParams);
	//
	// linearParams.height = s_h;
	// linearParams.width = s_w;
	// _view.setLayoutParams(linearParams);
	// if (_group_view != null) {
	// _group_view.setVisibility(View.VISIBLE);
	// }
	// }
	// }
	// }
	// }
	//
	// @Override
	// public void OnFail(String reason) {
	// }
	// }

	/**
	 * 屏蔽输入框emoji的输入
	 */
	public static InputFilter emojiFilter = new InputFilter() {
		Pattern emoji = Pattern
				.compile(
						"[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
						Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

		@Override
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {
			Matcher emojiMatcher = emoji.matcher(source);
			if (emojiMatcher.find()) {
				return "";
			}
			return null;
		}
	};

	/**
	 * 修改最后消息列表内容
	 *
	 * @param mQyxMsg
	 */
	public void updateTopMsg(QyxMsg mQyxMsg) {
		QyxMsg last = takeMsgManager.queryChatLast(mQyxMsg.from_cust_id,
				mQyxMsg.to_cust_id, mQyxMsg.sessionModel.getSessionId());

		QyxTopMsg mQyxTopMsg = new QyxTopMsg();
		if (last == null) {
			mQyxTopMsg.content = "";
			mQyxTopMsg.msg_content_type = MsgContentType.TEXT;
		} else {
			String content = MsgContentType2Name
					.GetMsgContentTypeName(last.msg_content_type);
			if (TextUtils.isEmpty(content)) {
				content = last.content;
			}
			mQyxTopMsg.content = content;
			mQyxTopMsg.msg_content_type = last.msg_content_type;
			mQyxTopMsg.msg_time = Long.parseLong(last.insert_time) / 1000;
		}
		if (mQyxMsg.sessionModel.getSessionType() == PacketType.PERSONAL) {
			if ((mQyxMsg.from_cust_id + "").equals(IMApplication.getCustId())) {
				topListMsgManager.updateLast(mQyxMsg.to_cust_id,
						mQyxMsg.sessionModel.getSessionType(), mQyxTopMsg);
			} else {
				topListMsgManager.updateLast(mQyxMsg.from_cust_id,
						mQyxMsg.sessionModel.getSessionType(), mQyxTopMsg);
			}
		} else if (mQyxMsg.sessionModel.getSessionType() == PacketType.GROUP) {
			topListMsgManager.updateLast(mQyxMsg.sessionModel.getSessionId(),
					mQyxMsg.sessionModel.getSessionType(), mQyxTopMsg);
		}
		/** 刷新首页数据 **/
		IMApplication.IS_REFRESH_TOP_MSG = true;

	}

	/**
	 * 得到回话列表中所有的图片类型的地址
	 *
	 * @param _msgList
	 *            回话集合
	 * @return
	 */
	public ArrayList<String> getMsgPicPaths(ArrayList<QyxMsgView> _msgList) {
		ArrayList<String> strs = new ArrayList<String>();
		if (_msgList != null && _msgList.size() > 0) {
			for (int i = 0, size = _msgList.size(); i < size; i++) {
				if (_msgList.get(i).msg.msg_content_type == MsgContentType.PIC) {
					String bigpath = "";
					MsgImageModel imageModel = (MsgImageModel) _msgList.get(i).msg.baseContentModel;
					if (imageModel != null) {
						AttachModel attachModel = (AttachModel) imageModel
								.getAttachmentModel();
						if (attachModel != null) {
							if (TextUtils.isEmpty(attachModel
									.getFileLocalPath())) {
								bigpath = APIConfiguration.getFileDownloadPath(
										attachModel.getFileId(),
										attachModel.getFileHash());
							} else {
								bigpath = attachModel.getFileLocalPath();
							}
							strs.add(bigpath);
						}
					}

				}
			}
		}
		return strs;
	}

	/**
	 * 得到语音按钮要显示的宽度
	 *
	 * @param durationTime
	 *            语音时间长度
	 * @param sound_msg_bg_total_width
	 *            总共长度
	 * @return
	 */
	public int getSoundBgWidth(int durationTime, int sound_msg_bg_total_width) {
		int diff_sound_width = sound_msg_bg_total_width;
		int sound_width = diff_sound_width / 60 * durationTime;
		double temp = 0;
		if (durationTime <= 10) {
			temp = 0.3;
		} else if (durationTime > 10 && durationTime <= 20) {
			temp = 0.5;
		} else if (durationTime > 20 && durationTime <= 30) {
			temp = 0.7;
		} else if (durationTime > 30 && durationTime <= 40) {
			temp = 0.9;
		} else if (durationTime > 40 && durationTime <= 60) {
			temp = 1;
		}
		sound_width = (int) ((int) diff_sound_width * temp);
		return sound_width;
	}

	/**
	 * // * 获取发送消息对象 // * // * @param qyxMsg // * 本地消息对象 // * @param chat_id //
	 * * 会话id(群聊：群id私聊：0) // * @param chatType // * 会话类型1:私聊2：群聊 // * @param
	 * to_cust_name // * 会话对方名称(群聊名称 | 好友名称) // * @param iSendMsgObject //
	 */
	// public void getSendMsgObject(QyxMsg qyxMsg, String chat_id, int chatType,
	// String to_cust_name, final ISendMsgObject iSendMsgObject) {
	// qyxMsg.from_cust_name = IMApplication.config.getUserName();
	// qyxMsg.from_cust_id = Long.parseLong(IMApplication.getCustId());
	// qyxMsg.to_cust_name = to_cust_name;
	// qyxMsg.chat_type = chatType;
	// qyxMsg.msg_type = MsgType.MSG_SENDS + "";
	// qyxMsg.send_status = "";
	// // 私聊
	// if (chatType == PacketType.PERSONAL) {
	// qyxMsg.chat_id = 0;
	// qyxMsg.to_cust_id = Long.valueOf(chat_id);
	// } else {
	// // 群聊
	// qyxMsg.chat_id = Long.valueOf(chat_id);// 群聊编号
	// qyxMsg.to_cust_id = 0;
	// }
	// // 发送消息
	// qyxMsg.msg_no = qyxMsg.getMsgNo(qyxMsg.from_cust_id + "",
	// qyxMsg.to_cust_id + "", qyxMsg.chat_id + "");
	// boolean is_send = false;
	// // 1文本、2图片、3动态图、4音频、5视频、6文件,16动态表情,17位置
	// switch (qyxMsg.category) {
	// case MsgContentType.TEXT:
	// is_send = true;
	// break;
	// case MsgContentType.PIC:
	// if (!TextUtils.isEmpty(qyxMsg.file_id)
	// && !TextUtils.isEmpty(qyxMsg.file_hash)) {// 转发消息
	// is_send = true;
	// } else {// 上传本地图片
	// is_send = false;
	// }
	// break;
	// case MsgContentType.AUDIO:
	// if (!TextUtils.isEmpty(qyxMsg.file_id)
	// && !TextUtils.isEmpty(qyxMsg.file_hash)) {// 转发消息
	// is_send = true;
	// } else {// 上传语音
	// is_send = false;
	// }
	// break;
	// case MsgContentType.FILE:
	// if (!TextUtils.isEmpty(qyxMsg.file_id)
	// && !TextUtils.isEmpty(qyxMsg.file_hash)) {// 转发消息
	// is_send = true;
	// } else {// 上传 文件
	// is_send = false;
	// }
	//
	// break;
	// case MsgContentType.GIF_EXP:
	// is_send = true;
	// break;
	// case MsgContentType.LOCATION:
	// is_send = true;
	// break;
	// case MsgContentType.BUSINESS_CRAD:
	// is_send = true;
	// break;
	// case MsgContentType.RED:
	// is_send = true;
	// break;
	// case MsgContentType.REQUEST_VIDEO_CHAT:
	// is_send = true;
	// break;
	// default:
	// break;
	// }
	//
	// iSendMsgObject.onSendMsgObject(qyxMsg, is_send);
	// }

	// /**
	// * 上传消息中的附件
	// *
	// * @param qyxMsg
	// * @param chat_id
	// * 会话id
	// * @param onAttachedListener
	// */
	// public void UploadMessageAttachment(QyxMsg qyxMsg, String chat_id,
	// OnAttachedListener onAttachedListener) {
	// if (TextUtils.isEmpty(qyxMsg.file_path)) {
	// return;
	// }
	//
	// byte[] file_bytes = null;
	// // 保存录音在本地数据库中
	// File file = new File(qyxMsg.file_path);
	// try {
	// file_bytes = Utils.getBytesFromFile(file);
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// String[] arrs = null;
	// try {
	// arrs = qyxMsg.file_path.split("\\.");// 后缀名
	// if (arrs.length < 2) {
	// arrs = qyxMsg.file_path.split("\\/");// 后缀名
	// }
	// } catch (Exception e) {
	// arrs[0] = "log";
	// arrs[1] = "error";
	// }
	//
	// new UploadMessageAttachment(file_bytes, arrs[arrs.length - 1],
	// mContext, onAttachedListener, chat_id);
	//
	// }

	public void UploadMessageAttachment(String file_path,
			OnAttachedListener onAttachedListener) {
		if (TextUtils.isEmpty(file_path)) {
			return;
		}

		byte[] file_bytes = null;
		// 保存录音在本地数据库中
		File file = new File(file_path);
		try {
			file_bytes = Utils.getBytesFromFile(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String[] arrs = null;
		try {
			arrs = file_path.split("\\.");// 后缀名
			if (arrs.length < 2) {
				arrs = file_path.split("\\/");// 后缀名
			}
		} catch (Exception e) {
			arrs[0] = "log";
			arrs[1] = "error";
		}

		new UploadMessageAttachment(file_bytes, arrs[arrs.length - 1],
				mContext, onAttachedListener);

	}

	/**
	 * 删除和撤销消息对象
	 *
	 * @author SL
	 *
	 */
	public interface IDeleteOrWithdrawMsg {
		/**
		 * 删除消息
		 *
		 * @param qyxMsg
		 */
		public abstract void onDeleteMsg(QyxMsg qyxMsg);

		/**
		 * 撤回消息
		 *
		 * @param qyxMsg
		 */
		public abstract void onWithdrawMsg(QyxMsg qyxMsg);
	};

	/**
	 * 发送消息对象
	 *
	 * @author SL
	 *
	 */
	public interface ISendMsgObject {
		/**
		 * 发送消息对象
		 *
		 * @param qyxMsg
		 * @param is_send
		 *            false表示该消息类型存在附件，必须先上传附件后才能发送消息
		 */
		public abstract void onSendMsgObject(QyxMsg qyxMsg, boolean is_send);
	};

	/**
	 * 收藏消息
	 *
	 * @param mQyxMsg
	 */
	private void collect(QyxMsg mQyxMsg) {
		String content = "", pic_url = "";
		if (mQyxMsg.msg_content_type == MsgContentType.TEXT) {
			content = mQyxMsg.content;
		} else if (mQyxMsg.msg_content_type == MsgContentType.PIC) {
			MsgImageModel imageModel = (MsgImageModel) mQyxMsg.baseContentModel;
			AttachModel attachModel = (AttachModel) imageModel
					.getAttachmentModel();
			if (attachModel != null) {
				pic_url = StringUtils.encodeParams(APIConfiguration
						.getFileDownloadPath(attachModel.getFileId(),
								attachModel.getFileHash()));
			}
		}

		mCollectHandle.addCollect(103, mQyxMsg.from_cust_id + "",
				mQyxMsg.from_cust_name, mQyxMsg.from_cust_name, content, "",
				pic_url, 0, null);
	}

	/**
	 * 获取红包
	 *
	 * @param red_id
	 * @param isToDetail
	 */
	public void getRed(String red_id, final boolean isToDetail) {
		if (!Utils.isNetworkConnected(mContext)) {
			IMApplication.showToast(R.string.network_disable);
			return;
		}
		RedHandler.pickRed(red_id, new RedHandler.IPickRedListener() {

			@Override
			public void onPickRed(int status, String msg,
								  ReceiveRedEntity mReceiveRedEntity) {
				if (status == HttpInvokeResultCode.RESULT_OK) {
					if (isToDetail || mReceiveRedEntity.isOpened == 1) {
						if (mReceiveRedEntity.tcustId != 0
								&& mReceiveRedEntity.chatid == 0) {
							Intent intent = new Intent(mContext,
									RedDetailPersonalActivity.class);
							intent.putExtra("mReceiveRedEntity",
									mReceiveRedEntity);
							mContext.startActivity(intent);
						} else {
							Intent intent = new Intent(mContext,
									RedDetailActivity.class);
							intent.putExtra("mReceiveRedEntity",
									mReceiveRedEntity);
							mContext.startActivity(intent);
						}
					} else {
						Intent intent = new Intent(mContext,
								ReceiveRedDialogActivity.class);
						intent.putExtra("mReceiveRedEntity", mReceiveRedEntity);
						mContext.startActivity(intent);
					}
				}
			}
		});
	}

	public void connectToRoom1(QyxMsg message, boolean loopback, int runTimeMs) {
		// String roomUrl = "http://121.40.57.130:8080";
		// String roomUrl = IMApplication.config.getRoomServer();
		String roomUrl = "http://107.150.60.234:8080";
		boolean videoCallEnabled = true;
		String videoCodec = "VP8";
		String audioCodec = "OPUS";
		boolean hwCodec = true;
		boolean noAudioProcessing = false;
		int videoWidth = 0;
		int videoHeight = 0;
		String resolution = "Default";
		String[] dimensions = resolution.split("[ x]+");
		if (dimensions.length == 2) {
			try {
				videoWidth = Integer.parseInt(dimensions[0]);
				videoHeight = Integer.parseInt(dimensions[1]);
			} catch (NumberFormatException e) {
				videoWidth = 0;
				videoHeight = 0;
				Log.e("video chat", "Wrong video resolution setting: "
						+ resolution);
			}
		}
		int cameraFps = 0;
		int videoStartBitrate = 0;
		int audioStartBitrate = 0;
		boolean cpuOveruseDetection = true;
		boolean displayHud = false;
		Log.d("video chat",
				"Connecting to room " + message.baseContentModel.getContent()
						+ " at URL " + roomUrl);
		if (validateUrl(roomUrl)) {
			Uri uri = Uri.parse(roomUrl);
			Intent intent = new Intent(mContext, CallActivity.class);
			intent.setData(uri);
			intent.putExtra("message", message);
			intent.putExtra(ExtraVideoConstant.EXTRA_ROOMID,
					message.baseContentModel.getContent());
			intent.putExtra(ExtraVideoConstant.EXTRA_LOOPBACK, loopback);
			intent.putExtra(ExtraVideoConstant.EXTRA_VIDEO_CALL,
					videoCallEnabled);
			intent.putExtra(ExtraVideoConstant.EXTRA_VIDEO_WIDTH, videoWidth);
			intent.putExtra(ExtraVideoConstant.EXTRA_VIDEO_HEIGHT, videoHeight);
			intent.putExtra(ExtraVideoConstant.EXTRA_VIDEO_FPS, cameraFps);
			intent.putExtra(ExtraVideoConstant.EXTRA_VIDEO_BITRATE,
					videoStartBitrate);
			intent.putExtra(ExtraVideoConstant.EXTRA_VIDEOCODEC, videoCodec);
			intent.putExtra(ExtraVideoConstant.EXTRA_HWCODEC_ENABLED, hwCodec);
			intent.putExtra(ExtraVideoConstant.EXTRA_NOAUDIOPROCESSING_ENABLED,
					noAudioProcessing);
			intent.putExtra(ExtraVideoConstant.EXTRA_AUDIO_BITRATE,
					audioStartBitrate);
			intent.putExtra(ExtraVideoConstant.EXTRA_AUDIOCODEC, audioCodec);
			intent.putExtra(ExtraVideoConstant.EXTRA_CPUOVERUSE_DETECTION,
					cpuOveruseDetection);
			intent.putExtra(ExtraVideoConstant.EXTRA_DISPLAY_HUD, displayHud);
			intent.putExtra(ExtraVideoConstant.EXTRA_CMDLINE, true);
			intent.putExtra(ExtraVideoConstant.EXTRA_RUNTIME, runTimeMs);

			mContext.startActivity(intent);
		}

	}

	private boolean validateUrl(String url) {
		if (URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url)) {
			return true;
		}
		return false;
	}

	/**
	 * 接受和发送的消息相互转换
	 *
	 * @param mQyxMsg
	 * @param msgContentType
	 */
	// public QyxMsg convertMsgAndSend(QyxMsg mQyxMsg, int msgContentType) {
	// QyxMsg msg = new QyxMsg();
	// msg.category = msgContentType;
	// msg.from_cust_id = mQyxMsg.from_cust_id;
	// msg.from_cust_name = mQyxMsg.from_cust_name;
	// msg.to_cust_id = mQyxMsg.to_cust_id;
	// //msg.sessionModel.setSessionType(mQyxMsg.sessionModel.getOperationType());
	// msg.msg_type = MsgType.MSG_SENDS + "";
	// msg.content = mQyxMsg.msg_no;
	// //msg.chat_id = mQyxMsg.chat_id;
	// msg.sessionModel = mQyxMsg.sessionModel;
	// msg.msg_no = msg.getMsgNo(msg.from_cust_id + "", msg.to_cust_id + "",
	// msg.sessionModel.getSessionId() + "");
	// return msg;
	// }

	/**
	 * 检查是否可以撤销消息
	 *
	 * @param msg
	 * @param iDeleteMsg
	 */
	private void checkMsgTime(QyxMsg msg, final IDeleteOrWithdrawMsg iDeleteMsg) {
		long nowDate = DateUtils.getCurrentSeconds();
		if (nowDate - msg.msg_time >= 120) {
			DialogUtility.showSingleBtnDialog(mContext,
					R.string.can_not_withdraw, R.string.sure, true,
					new IOnBottomDialogListener() {

						@Override
						public void onClicked() {
						}
					});
		} else {
			iDeleteMsg.onWithdrawMsg(msg);
			Intent intent = new Intent(mContext, DialogLoadingActivity.class);
			mContext.startActivity(intent);
		}
	}

	/**
	 * 添加表情
	 *
	 * @param msg
	 */
	private void addSticker(QyxMsg msg) {
		if (msg != null && msg.baseContentModel != null) {
			MsgGifModel msgGifModel = (MsgGifModel) msg.baseContentModel;
			if (msgGifModel != null
					&& !TextUtils.isEmpty(msgGifModel.getFileId())
					&& !TextUtils.isEmpty(msgGifModel.getFileHash())) {
				JSONObject jsonObject = new JSONObject();
				try {
					jsonObject.put("fileid", msgGifModel.getFileId());
					jsonObject.put("filehash", msgGifModel.getFileHash());
				} catch (JSONException e) {
					e.printStackTrace();
				}
				StickersHandle.addSticker(jsonObject.toString(),
						new StickersHandle.IAddStickerListener() {

							@Override
							public void onAddStrickerResult(int status,
															String msg, String favoriteid) {
								if (status == HttpInvokeResultCode.RESULT_OK) {
									IMApplication
											.getAppContext()
											.sendBroadcast(
													new Intent(
															BroadcastAction.ACTION_REFRESH_STICKER));
								} else if (!TextUtils.isEmpty(msg)) {
									IMApplication.showToast(msg);
								}
							}
						});
			}

		}
	}
}
